package com.alipay.rebate.shop.scheduler.orderimport;

import com.alipay.rebate.shop.constants.UserIncomeConstant;
import com.alipay.rebate.shop.dao.mapper.*;
import com.alipay.rebate.shop.helper.UserIncomeBuilder;
import com.alipay.rebate.shop.model.Orders;
import com.alipay.rebate.shop.model.RefundOrders;
import com.alipay.rebate.shop.model.UserIncome;
import com.alipay.rebate.shop.pojo.user.admin.AdminImportRefundOrdersReq;
import com.alipay.rebate.shop.pojo.user.admin.RefundOrdersImpoertReq;
import com.alipay.rebate.shop.utils.ListUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Component
public class AdminImportRefundOrders {

    @Autowired
    RefundOrdersMapper refundordersMapper;


    @Autowired
    OrdersMapper ordersMapper;

    @Autowired
    UserIncomeMapper userIncomeMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserGradeMapper userGradeMapper;



    private Logger logger = LoggerFactory.getLogger(AdminImportRefundOrders.class);

    Gson gson = new GsonBuilder().create();


    public void importRefundOrders(AdminImportRefundOrdersReq refundOrdersReq) throws ParseException {

        logger.debug("refundOrdersReq start");
        List<RefundOrdersImpoertReq> refundOrders = refundOrdersReq.getOrders();

        //获取所有订单信息
        for (RefundOrdersImpoertReq refundOrder : refundOrders){

            logger.debug("refundOrder is : {}",refundOrder);
            //准备订单
            RefundOrders refundOrders1 = buildRefundOrders(refundOrder);

            //处理维权订单
            handleRefundOrder(refundOrders1);

        }

    }

    //处理维权订单
    public void handleRefundOrder(RefundOrders refundOrder) throws ParseException {

        logger.debug("handleRefundOrder start");
        //获取的淘宝订单信息
        Orders orders = ordersMapper.selectOrdersByTradeId(refundOrder.getTbTradeId());

        logger.debug("orders is : {}",orders);

        //根据订单号获取维权订单信息是否已经存在
        RefundOrders refundOrders = refundordersMapper.selectById(refundOrder.getTbTradeId());

        if (refundOrders != null && refundOrders.getRefundStatus() == 2){
            //此订单已维权成功且记录已存在不做处理
            logger.debug("refund is ");
            return;
        }
        if (orders != null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (orders.getCreateTime() != null) {
                Date date = sdf.parse(orders.getCreateTime());
                refundOrder.setTbTradeCreateTime(date);
            }
            refundOrder.setTbTradeId(refundOrder.getTbTradeId());
            refundOrder.setTbTradeParentId(orders.getTradeParentId());
            refundOrder.setTk3rdPubId(orders.getTk3rdPubId());
            refundOrder.setRelationId(orders.getRelationId());
            refundOrder.setUserId(orders.getUserId());
            refundOrder.setSpecialId(orders.getSpecialId());
        }

        //保存或更新维权订单记录
        saveOrUpdateOrderWhenNotComplete(refundOrders,refundOrder);


        logger.debug("refundOrders.getRefundStatus is : {}",refundOrder.getRefundStatus());
        // 如果是维权成功状态，那么相应减掉用户收益(集分宝)
        if(refundOrders.getRefundStatus() == 2){

            logger.debug("refundOrders.getRefundStatus() : {}",refundOrder.getRefundStatus());


//            //计算维权成功后用户可以获得的佣金
//            //获取预估佣金
//            BigDecimal pubSharePreFee = orders.getPubSharePreFee();
//
//            //获取分销商等级比例
//            UserGrade grade = userGradeMapper.selectUserGrade();
//
//            //判断用户收益否还在冻结中


            // 查询订单收益列表
            List<UserIncome> userIncomeList = userIncomeMapper
                    .selectUserIncomeByOrdersId(orders.getTradeId());
            // 如果用户确实获取了收益
            if(!ListUtil.isEmptyList(userIncomeList)){
                for(UserIncome userIncome: userIncomeList){
                    long userId = userIncome.getUserId();
                    BigDecimal money = userIncome.getMoney();
                    long uit = money.multiply(new BigDecimal("100")).longValue();
                    // 如果已经转账给用户，那么进行扣款
                    if(UserIncomeConstant.IS_PAID == userIncome.getStatus()){
                        if(uit >0){
                            userMapper.plusUserUit(-uit,userId);
                        }
                    }else{// 否则，更改状态(TODO mingweicai)
                        // 将收益状态更改为已经付款
                        UserIncome nU = new UserIncome();
                        nU.setUserIncomeId(userIncome.getUserIncomeId());
                        nU.setStatus(UserIncomeConstant.IS_PAID);
                        userIncomeMapper.updateByPrimaryKeySelective(nU);
                    }
                    // 插入用户扣款记录
                    Integer type = UserIncomeConstant.REFUND_UN_AWAED_TYPE;
                    Integer isPaid = UserIncomeConstant.IS_PAID;
                    UserIncome nUserIncome = UserIncomeBuilder
                            .buildUitPaidUserIncome(orders, money.negate(),type,userId,isPaid);
                    userIncomeMapper.insertSelective(nUserIncome);
                }
            }
        }

    }


    private void saveOrUpdateOrderWhenNotComplete(RefundOrders previousRefundOrders,
                                                  RefundOrders refundOrders){
        if(previousRefundOrders == null){
            logger.debug("insert refundOrders");
            refundordersMapper.insertSelective(refundOrders);
        }else{
            logger.debug("update refundOrders");
            refundordersMapper.updateByPrimaryKeySelective(refundOrders);
        }
    }


    //准备订单信息
    private RefundOrders buildRefundOrders(RefundOrdersImpoertReq req) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.parse(req.getEstimateTime());
        RefundOrders refundOrders = new RefundOrders();
        refundOrders.setTbTradeId(req.getTkTradeId());

        if (req.getEstimateTime() != null){
            refundOrders.setEarningTime(sdf.parse(req.getEstimateTime()));
        }
        if (req.getStaterTime() != null){
            refundOrders.setTkRefundTime(sdf.parse(req.getStaterTime()));
        }

        refundOrders.setRefundStatus(req.getRefundStatus());
        refundOrders.setTkPubId(196240035l);
        if (req.getFinishTime() != null){
            refundOrders.setTkRefundSuitTime(sdf.parse(req.getFinishTime()));
        }
        refundOrders.setTbAuctionTitle(req.getProductName());
        return refundOrders;

    }

}
